package com.customview.wzq.recycleviewdemo;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;

//实现可以点击的，有分割线的rv
public class MainActivity extends AppCompatActivity {

    private RecyclerView mRv;
    private RecyclerAdapter mRvAdapter;
    private List<MyData> mData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

      // doTest();
        mRv = (RecyclerView) this.findViewById(R.id.rv_main);
        initView();
        initData();
    }

    private void doTest() {
      /*  String item1="kb";
        String item2="jay";
        List<String> data=new ArrayList<>();
        data.add(item1);
        data.add(item2);*/
      String data="['kb','jay']";
        try {
            JSONArray jsonArray = new JSONArray(data);
            for (int i = 0; i < jsonArray.length(); i++) {
                Log.d("kb_jay_test",jsonArray.optString(i));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    private void initData() {
        mData.clear();
        for(int i = 0 ;i < 100;i++){
            mData.add(new MyData(i));
        }
        mRvAdapter.notifyDataSetChanged();
    }

    private void initView() {
        mData= new ArrayList<>();
        mRvAdapter = new RecyclerAdapter(mData);
        //设置点击事件
        mRvAdapter.setCustomListener(new RecyclerAdapter.CustomListener() {
            @Override
            public void onItemClick(int position) {
                Toast.makeText(MainActivity.this, Integer.toString(mData.get(position).number), Toast.LENGTH_SHORT).show();
            }
        });
        //设置layoutManager  垂直，水平，grid三种
       // mRv.setLayoutManager(new LinearLayoutManager(this));
        mRv.setLayoutManager(new GridLayoutManager(this,3));
        //设置自定的decoration（用于绘制item的边缘）
       // mRv.addItemDecoration(new RecyclerDivider(this));
        mRv.addItemDecoration(new GridDivider(this,3));

        mRv.setAdapter(mRvAdapter);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        Log.d("kb_jay",keyCode+"=========");
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();

        Log.d("kb_jay","back pressed!!!");
    }
}
